package com.xyf.sys.util;

import com.wechat.pay.java.core.util.PemUtil;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Base64;
import java.util.Random;

/**
 * @Author R-H
 * @Date 2024/2/241809
 * @Description
 */
public class WechatPayUtil {

    /**
     * 获取随机数
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(59);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String sha256WithRsa(String appid, String timestamp, String nonce, String packageStr, String privateKey) {
        try {
            String str = appid + "\n" + timestamp + "\n" + nonce + "\n" + packageStr + "\n";
            Signature sign = Signature.getInstance("SHA256withRSA");
            // 使用私钥进行初始化签名(私钥需要从私钥文件【证书】中读取)
            sign.initSign(PemUtil.loadPrivateKeyFromString(privateKey));
            // 签名更新
            sign.update(str.getBytes(StandardCharsets.UTF_8));
            // 对签名结果进行Base64编码
            return Base64.getEncoder().encodeToString(sign.sign());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }
}
